package com.mosai.alignpro.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.text.TextUtils;
import android.view.ContextThemeWrapper;

import java.util.Locale;

/**
 * Created by Rays on 2020/4/14.
 */
public final class LanguageUtils {

    private static Locale locale;

    public static void setLanguage(String language) {
        if (TextUtils.isEmpty(language)) {
            return;
        }
        switch (language) {
            case "en":
                locale = Locale.ENGLISH;
                break;
            case "ja":
                locale = Locale.JAPAN;
                break;
            default:
                locale = Locale.CHINESE;
                break;
        }

    }

    public static Context attachBaseContext(Context context) {
        if (locale != null) {
            context = setAppLanguage(context, locale);
        }
        return fixAndroidx(setFontScale(context));
    }

    /**
     * 更新应用语言
     */
    @SuppressLint("ObsoleteSdkInt")
    private static Context setAppLanguage(Context context, Locale locale) {
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();

        if (configuration.fontScale != 1.0f) {
            configuration.fontScale = 1.0f;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            configuration.setLocale(locale);
            return context.createConfigurationContext(configuration);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return context;
    }

    public static ContextThemeWrapper fixAndroidx(Context context) {
        //兼容androidx appcompat 1.2.0后切换语言失效问题
        final Configuration configuration = context.getResources().getConfiguration();
        return new ContextThemeWrapper(context, null) {
            @Override
            public void applyOverrideConfiguration(Configuration overrideConfiguration) {
                if (overrideConfiguration != null) {
                    overrideConfiguration.setTo(configuration);
                }
                super.applyOverrideConfiguration(overrideConfiguration);
            }
        };
    }

    /**
     * 更新应用语言
     */
    private static Context setFontScale(Context context) {
        Configuration configuration = context.getResources().getConfiguration();
        if (configuration.fontScale != 1.0f) {
            configuration.fontScale = 1.0f;
            return context.createConfigurationContext(configuration);
        }
        return context;
    }
}
